package com.spark.incoicings.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.spark.incoicings.dao.CustomerMapper;
import com.spark.incoicings.dao.OrderDetailMapper;
import com.spark.incoicings.dao.ProductMapper;
import com.spark.incoicings.dao.SalesOrderMapper;
import com.spark.incoicings.service.DictTypeService;
import com.spark.incoicings.utils.RandomGenerateUtil;
import com.spark.incoicings.vo.CustomerVO;
import com.spark.incoicings.vo.DictVO;
import com.spark.invoicings.entity.*;
import com.spark.invoicings.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hpsf.Decimal;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/login")
@Slf4j
public class SaleOrderController {

    @Resource
    private DictTypeService dictTypeService;
    @Resource
    private SalesOrderMapper salesOrderMapper;
    @Resource
    private CustomerMapper customerMapper;
    @Resource
    private RandomGenerateUtil randomGenerateUtil;
    @Resource
    private OrderDetailMapper orderDetailMapper;
    @Resource
    private ProductMapper productMapper;
    /**
     * 查询订单状态
     * @return
     */
    @GetMapping("/selectStatus")
    public Result selectStatus(){
        List<DictVO> status = dictTypeService.selectStatus();
        return Result.success(200,"success",status);
    }
    @GetMapping("/selectState")
    public Result selectState(){
        List<DictVO> state = dictTypeService.selectState();
        return Result.success(200,"success",state);
    }
    @GetMapping("/selectSaleOrderAll")
    public Result selectSaleOrderAll(@RequestParam(defaultValue = "1")Integer pageNum,
                                     @RequestParam(defaultValue = "3")Integer pageSize,
                                     @RequestParam(required = false)String orderTime,
                                     @RequestParam(required = false)Integer status,
                                     @RequestParam(required = false)String customerName
                                     ){
        PageHelper.startPage(pageNum,pageSize);
        Map<String, Object> map = new HashMap<>();
        map.put("orderTime",orderTime);
        map.put("status",status);
        map.put("customerName",customerName);
        List<SalesOrder> salesOrders;
        try{
             salesOrders = salesOrderMapper.selectSalesOrderAll(map);
        }catch (NullPointerException e){
            e.printStackTrace();
            return Result.success();
        }
        if (salesOrders != null) {
            salesOrders.forEach(salesOrder -> {
                if (salesOrder != null && salesOrder.getCustomer() != null) {
                    DictVO dict = dictTypeService.selectDictTow(salesOrder.getOrderId());
                    if (dict != null) {
                        salesOrder.setStatus(dict.getStatus());
                    }
                    CustomerVO customerVO = customerMapper.selectCustomerVo(salesOrder.getCustomer().getCustomerId());
                    if (customerVO != null) {
                        salesOrder.getCustomer().setCustomerRating(customerVO.getCustomerRating());
                        salesOrder.getCustomer().setCustomerSource(customerVO.getCustomerSource());
                        salesOrder.getCustomer().setBillingMethod(customerVO.getBillingMethod());
                    }
                }
            });
        }
        PageInfo<SalesOrder> follow = new PageInfo<>(salesOrders);
        return Result.success(200,"success",follow);
    }

    /**
     * 添加订单接口1.0
     * @param
     * @return
     */
//    @PostMapping("/saveSaleOrder")
//    public Result saveSaleOrder(@RequestBody SalesOrder order){
//        double countPrice = 0.00;//总金额
//        double totalProfit = 0.00;//总利润
//        double totalCost = 0.00;//总成本
//        log.info("order={}",order);
//        Code code = new Code();
//        code.setType("DD");
//        code.setText(code.getType()+"%s%s");
//        String orderNum = randomGenerateUtil.nextSerialNumber(code);
//        order.setOrderNumber(orderNum);
//        salesOrderMapper.insert(order);
//        for (OrderDetail orderDetail: order.getOrderDetail()){
//            //销售订单id
//            orderDetail.setSalesOrderId(order.getOrderId());
//            //订单明细总额
//            orderDetail.setSubtotalAmount(orderDetail.getQuantityOrdered()*orderDetail.getDiscountedPrice());
//            //统计销售总金额
//            countPrice+=orderDetail.getSubtotalAmount();
//            //订单明细商品成本
//            orderDetail.setProductCost(orderDetail.getCostPrice()*orderDetail.getQuantityOrdered());
//            //统计总成本
//            totalCost+=orderDetail.getProductCost();
//            //待申请发货数量
//            orderDetail.setPendingShipmentQuantity(orderDetail.getQuantityOrdered());
//            //待收金额
//            orderDetail.setPendingPaymentAmount(orderDetail.getSubtotalAmount());
//            orderDetailMapper.insert(orderDetail);
//        }
//        order.setOrderTotalAmount(countPrice);
//        totalProfit = countPrice-totalCost;
//        order.setTotalProfit(totalProfit);
//        order.setTotalCostOfGoods(totalCost);
//        double profitPercentage = (totalProfit / countPrice) * 100;
//        order.setOrderGrossMargin(profitPercentage);
//        order.setSalesCommission(countPrice*(3.0/100));
//        order.setPendingCollectionAmount(countPrice);
//        salesOrderMapper.updateById(order);
//        return Result.success(200,"success",order);
//    }
    @PostMapping("/saveSaleOrder")
    public Result saveSaleOrder(@RequestBody SalesOrder order){
        if (order!=null){
        Code code = new Code();
        code.setType("DD");
        code.setText(code.getType()+"%s%s");
        String orderNum = randomGenerateUtil.nextSerialNumber(code);
        order.setOrderNumber(orderNum);
            int insert = salesOrderMapper.insert(order);
            if (!(order.getOrderDetail()!= null && insert < 1)){
                order.getOrderDetail().forEach(orderDetail -> {
                    orderDetail.setSalesOrderId(order.getOrderId());
                    orderDetailMapper.insert(orderDetail);
                });
            }else {
                return Result.error(400,"添加订单失败");
            }
        }
        return Result.success(200,"success",order);
    }
    @PostMapping("/updateSaleOrder")
    public Result updateSaleOrder(@RequestBody SalesOrder salesOrder){
        salesOrderMapper.updateById(salesOrder);
        return Result.success(200,"success",salesOrder);
    }
    @GetMapping("/selectSaleOrder")
    public Result saleSaleOrder(Integer id){
        SalesOrder salesOrder = salesOrderMapper.selectById(id);
        SaleCustomer saleCustomer = customerMapper.selectById(salesOrder.getCustomerId());
        salesOrder.setCustomer(saleCustomer);
        List<OrderDetail> orderDetails = orderDetailMapper.selectList(new QueryWrapper<OrderDetail>().eq("sales_order_id", salesOrder.getOrderId()));
        salesOrder.setOrderDetail(orderDetails);
        orderDetails.forEach(orderDetail -> {
            Product product = productMapper.selectById(orderDetail.getProductId());
            orderDetail.setProducts(product);
        });
        return Result.success(200,"success",salesOrder);
    }
    @GetMapping("/selectSaleOrderByCustomerId")
    public Result selectSaleOrderByCustomerId(Integer id){
        List<SalesOrder> salesOrders = salesOrderMapper.selectList(new QueryWrapper<SalesOrder>().eq("customer_id",id));
        salesOrders.forEach(salesOrder -> {
            SaleCustomer saleCustomer = customerMapper.selectById(salesOrder.getCustomerId());
            salesOrder.setCustomer(saleCustomer);
            DictVO dict = dictTypeService.selectDictTow(salesOrder.getOrderId());
            salesOrder.setStatus(dict.getStatus());
        });
        return Result.success(200,"success",salesOrders);
    }

    /**
     * 修改订单状态
     * @return
     */
    @PostMapping("/updateOrderStatus")
    public Result updateOrderStatus(@RequestBody SalesOrder order){
        salesOrderMapper.updateById(order);
        return Result.success();
    }

    /**
     * 删除订单,已审批订单不能删除
     * @param id
     * @return
     */
    @PostMapping("/deleteSalesOrder")
    public Result deleteSalesOrder(Integer id){
        SalesOrder salesOrder = salesOrderMapper.selectById(id);
        if (salesOrder.getOrderStatusId()==110 || salesOrder.getOrderStatusId()==116 || salesOrder.getOrderStatusId()==117){
            customerMapper.deleteById(id);
            return Result.success();
        }
        return Result.error(400,"已审批订单不能删除");
    }
}
